<?php
require 'tag/tag.php';

//解析模板中的变量与标签
class Compile extends Tag{
	//模板内容
	protected $content;

	//解析类入口
	protected function compileTpl($content)
	{
		$this->content =$content;

		//解析变量
		$this->parseVars();

		//解析标签
		$this->parseTag();

		return $this->content;
	}

	//解析变量
	private function parseVars()
	{
		//{{$web}}   <?php echo $web;? >
		$pattern='/\{\{(.*?)\}\}/i';
		$replacement='<?php echo \1;?>';
		$this->content =  preg_replace($pattern, $replacement, $this->content);
	}

	//解析标签
	private function parseTag()
	{
		$obj = new Tag;
		//获取对象属性
		$tags = $obj->tag;
		// 遍历属性
		// print_r($tags);exit;
		
		foreach($tags as $tag=>$params)
		{	

			// print_r($tags);exit;
			// <stu row='10' where="sex=2">  $tag 为键名
			$preg = '/<'.$tag.'(.*?)>(.*?)<\/'.$tag.'>/is';
			// print_r($preg);exit;
			// preg_match_all() 函数用于进行正则表达式全局匹配，成功返回整个模式匹配的次数
			//最后一个参数PREG_SET_ORDER：对结果排序使 $matches[0] 为第一组匹配项的数组，$matches[1] 为第二组匹配项的数组，以此类推
			//返回的是整个匹配的次数
			if(preg_match_all($preg, $this->content, $matches,PREG_SET_ORDER))
			{
				foreach($matches as $t)
				{	
					print_r($t);exit;
					//标签属性
					$attr = $this->getTagAttr($t[1]);
					// print_r($attr);
					//标签内容
					$body = $t[2];
					$method= '_'.$tag;
					$replace = $obj->$method($attr,$body);
					$this->content = str_replace($t[0], $replace, $this->content);
				}
			}
		}
	}

	//获取标签属性
	private function getTagAttr($str)
	{
		$attr=[];

		$preg = '/(\w+?)=[\'"](.+?)[\'"]/i';
		if(preg_match_all($preg, $str, $matches,PREG_SET_ORDER))
		{
			foreach($matches as $v)
			{
				$attr[$v[1]]=$v[2];
			}
		}
		return $attr;
	}
}













